var home = require("../../utils/util.js");
var url = home.home;
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    page: 1,
    stockId: home.getKey('stockId'), //股东id
    storeId: app.globalData.storeId,
    tokerData: [],
    show9: false, //海报
    loadImagePath: '',
    show7: false,
    vipJson: {},
    bgcolor: home.getKey('bgcolor'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  regiser() {
    wx.showLoading({
      title: '加载中...',
    });
    let that = this;
    wx.login({
      success(res) {
        wx.request({
          url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/register?storeId=' + app.globalData.storeId + '&code=' + res.code,
          data: {
            storeId: app.globalData.storeId,
            code: res.code
          },
          method: 'POST',
          header: {
            "content-type": "application/json", // 默认
          },
          success: function (rea) {
            if (rea.data.code == 200) {
              home.setKey('storeId', rea.data.result.member.storeId);
              home.setKey('stockId', rea.data.result.member.stockId);
              home.setKey('userId', rea.data.result.member.id);
              home.setKey('phone', rea.data.result.member.phone);
              home.setKey('openId', rea.data.result.member.xcxOpenId);
              home.setKey('unionId', rea.data.result.member.unionId);
              that.setData({
                stockId: rea.data.result.member.stockId,
                storeId: rea.data.result.member.storeId
              })
              wx.hideLoading({
                success: (res) => {
                  that.getUserInfos();
                },
              })
            } else {
              home.wxMessage(rea.data.message, 'none');
            }
          }
        })
      }
    })
  },

  //获取用户数据
  getUserInfos() {
    let that = this;
    wx.request({
      url: url + 'app/getUserInfo',
      data: {
        storeId: home.getKey('storeId'),
        phone: home.getKey('phone'),
        xcxOpenId: home.getKey('openId'),
      },
      method: 'GET',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          if (res.data.result.discount == null) {
            res.data.result.discount = 10
          }
          if (res.data.result.balance == null) {
            res.data.result.balance = 0;
          }
          if (res.data.result.stockLowest == null) {
            res.data.result.stockLowest = 0;
          }
          if (res.data.result.equityBalance == null) {
            res.data.result.equityBalance = 0;
          }
          if (res.data.result.totalDividend == null) {
            res.data.result.totalDividend = 0;
          }
          if (res.data.result.equityTotal == null) {
            res.data.result.equityTotal = 0;
          }
          home.setKey('discount', res.data.result.discount);
          home.setKey('equityBalance', res.data.result.equityBalance);
          home.setKey('balance', res.data.result.balance);
          home.setKey('levelName', res.data.result.levelName);
          home.setKey('stockLowest', res.data.result.stockLowest);
          home.setKey('stockId', res.data.result.stockId);
          home.setKey('birthday', res.data.result.birthday);
          home.setKey('equityTotal', res.data.result.equityTotal);
          home.setKey('nickName', res.data.result.nickName);
          home.setKey('canWithdrawal', res.data.result.canWithdrawal);
          home.setKey('noUseEquityBalancd', res.data.result.noUseEquityBalancd);
          home.setKey('avatar', res.data.result.headProtrait);
          that.setData({
            stockId: res.data.result.stockId
          })
          that.getTokerList();
        }
      }
    })
  },

  //查询股东拓客卡列表
  getTokerList() {
    let that = this;
    wx.request({
      url: url + 'app/stock/vipList',
      data: {
        storeId: home.getKey('storeId'),
        stockId: home.getKey('stockId'),
        pageNo: that.data.page,
        pageSize: 10,
      },
      method: 'GET',
      header: {
        "content-type": "application/json", // 默认 
      },
      success: function (res) {
        if (res.data.code == 200) {
          let tokerData = that.data.tokerData;
          if (that.data.page == 1) {
            tokerData = res.data.result;
          } else {
            for (let i = 0; i < res.data.result.length; i++) {
              tokerData.push(res.data.result[i]);
            }
          }
          let show7 = false;
          if (tokerData.length == 0) {
            show7 = true;
          }
          that.setData({
            tokerData: tokerData,
            show7: show7
          });
        } else {
          wx.showToast({
            title: '获取失败,请稍后再试',
            icon: 'none'
          });
        }
      }
    })
  },

  showPopup(e) {
    let id = e.currentTarget.dataset.id;
    let json = {};
    for (let i = 0; i < this.data.tokerData.length; i++) {
      if (this.data.tokerData[i].id == id) {
        json = this.data.tokerData[i];
      }
    }
    json.shareId = json.id;
    home.setKey('posterName', json.cardName);
    //判断接口返回的videoid>0有视频，设置分享参数
    if(json.vedioId>0){
      json.path = '/pages/shipin/index?vipId='+json.id+'&type=4'
    }else{
      json.path = '/shop/guest/info?type=4&id=' + json.id // 路径，传递参数到指定页面。
    }
    console.log(json);
    this.setData({
      show: true,
      vipJson: json
    });
  },

  getShareId() {
    let json = this.data.vipJson;
    let that = this;
    wx.request({
      url: url + 'app/shareVip',
      data: {
        shareVipId: json.id,
        storeId: home.getKey('storeId'),
        memberId: home.getKey('userId'),
        type: '2'
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          json.shareId = res.data.result.toReceiveVipId;
          that.setData({
            vipJson: json,
          })
        }
      }
    })
  },

  onClose() {
    this.setData({
      show: false
    });
  },

  //跳转优惠券列表
  toDoesList(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../../shop/guest/info?type=5&id=' + id,
    })
  },

  onClose2() {
    this.setData({
      show9: false
    });
  },

  qrcode(shareVipId) {
    wx.request({
      url: url + 'app/shareVip',
      data: {
        storeId: home.getKey('storeId'),
        memberId: home.getKey('userId'),
        type: "1",
        shareVipId: shareVipId,
        page: 'shop/guest/info',
        //page2: 'pages/shipin/index',
        env_version: 'trial',
      },
      responseType: 'arraybuffer',
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认 
      },
      success: function (res) {
        console.log('---------------------------')
        console.log(res.data)//小程序码是后台生成的64位图片
        console.log('---------------------------')
        let file = wx.getFileSystemManager();
        let filePath = wx.env.USER_DATA_PATH + '/qrcode.png';
        file.writeFile({
          filePath: filePath,
          data: wx.arrayBufferToBase64(res.data),
          encoding: 'base64',
          success(rea) {
            console.log(rea);
          }
        })
      }
    })
  },

  hb() {
    let that = this;
    this.qrcode(this.data.vipJson.id);
    setTimeout(function () {
      that.hb1();
    }, 1000);
  },

  hb1() {
    let storePhone = home.getKey('storePhone');
    let storeCity = home.getKey('storeCity');
    let storeName = home.getKey('storeName');
    let posterName = home.getKey('posterName');
    this.setData({
      show9: true,
      show1: false,
      show: false
    });
    let height = wx.getSystemInfoSync().windowHeight * 0.8;
    if (wx.getSystemInfoSync().windowHeight == 504) {
      height = wx.getSystemInfoSync().windowHeight - 40;
    }

    let width = wx.getSystemInfoSync().windowWidth - 40;
    this.setData({
      height: height,
      width: width
    })
    let that = this;
    const query = wx.createSelectorQuery()
    query.select('#myCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');

        const dpr = wx.getSystemInfoSync().pixelRatio;
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr);
        ctx.fillRect(0, 0, width, 0);

        //绘制背景图
        wx.getImageInfo({
          src: "https://kyz.fbhkj.com/canvas_back.png",
          success: (res) => {
            let imageUrl = res.path // 图片临时地址
            let imageW = res.width
            let imageH = res.height
            let ratio = wx.getSystemInfoSync().pixelRatio // 获取比例
            // 1. 创建一个图片对象。支持在 2D Canvas 和 WebGL Canvas 下使用, 但不支持混用 2D 和 WebGL 的方法。
            let imageObj = canvas.createImage()
            // 2. 给创建的图片对象的src赋值
            imageObj.src = imageUrl;
            let qrcodeImg = canvas.createImage();
            qrcodeImg.src = wx.env.USER_DATA_PATH + '/qrcode.png';
            // 3. 图片加载完之后触发
            imageObj.onload = () => {
              // 4. 绘制图片
              ctx.drawImage(imageObj, 0, 20, width, height);
              //绘制文本
              ctx.font = 'italic bold 25px Arial';
              ctx.fillStyle = 'white';
              ctx.textAlign = 'center';
              ctx.fillText(storeName, width / 2, height / 2 * 0.35);
              ctx.font = '12px Arial';
              ctx.fillStyle = '#fff';
              ctx.textAlign = 'center';
              ctx.fillText('电话:' + storePhone, width / 2, height / 2 * 0.53);
              ctx.font = '12px Arial';
              ctx.fillStyle = '#fff';
              ctx.textAlign = 'center';
              ctx.fillText('地址:' + storeCity, width / 2, height / 2 * 0.6);
              ctx.font = 'bold 20px Arial';
              ctx.fillStyle = '#D19C46';
              ctx.textAlign = 'center';
              ctx.fillText(posterName, width / 2, height / 2 * 1.2);
              ctx.drawImage(qrcodeImg, width / 2 * 0.72, height / 2 * 1.32, 85, 85);
              setTimeout(() => {
                that.toSave(canvas, width, height);
              }, 1000);
            }
          },
          fail: (err) => {}
        })
      })
  },

  toSave(canvas, width, height) {
    let that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 20,
      width: width,
      height: height,
      destWidth: width * wx.getSystemInfoSync().pixelRatio,
      destHeight: height * wx.getSystemInfoSync().pixelRatio,
      canvasId: 'myCanvas',
      canvas: canvas,
      success(res) {
        var tempFilePath = res.tempFilePath;
        that.setData({
          loadImagePath: tempFilePath,
        });
      }
    })
    
  },

  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.loadImagePath,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              /* 该隐藏的隐藏 */
            }
          },
          fail: function (res) {
            console.log(11111)
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.regiser();
    // 打开调试
    // wx.setEnableDebug({
    //   enableDebug: true
    // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // let page = this.data.page;
    // this.setData({
    //   page: ++page
    // });
    // this.getTokerList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let json = this.data.vipJson;
    console.log(json);
    wx.request({
      url: url + 'app/shareVip',
      data: {
        storeId: home.getKey('storeId'),
        memberId: home.getKey('userId'),
        type: "2",
        shareVipId: json.id,
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认 
      },
      success: function (res) {}
    })
    return {
      title: json.cardName,
      //imageUrl: 'https://kyz.fbhkj.com/fubaihui/' + json.detailsUrl,
      imageUrl: 'https://kyz.fbhkj.com//' + json.detailsUrl,
      path: json.path
      //path: '/shop/guest/info?type=4&id=' + json.id // 路径，传递参数到指定页面。
    }
  }
})